import json

from django.shortcuts import render
from db_man_app.models import Department,Major, Class, Student
from django.db.models import Count
from django.http import JsonResponse

# Create your views here.
def get_all(request):
    # 获取所有学院及其关联数据
    departments = Department.objects.annotate(
        major_count=Count('major', distinct=True),
        class_count=Count('major__class', distinct=True),
        student_count=Count('major__class__student', distinct=True)
    ).all()
    # 构建返回数据
    tableData = []
    for dept in departments:
        tableData.append({
            'college_name': dept.department_name,
            'major_number': dept.major_count,
            'class_number': dept.class_count,
            'college_p_number': dept.student_count
        })
    return JsonResponse({
        'tableData': tableData,
        'status': 'success',
        'message': '数据获取成功'
    })

def add_one(request):
    try:
        data = json.loads(request.body)
        college_name= data['college_name']
        Department.objects.create(department_name=college_name)
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)

def updata_one(request):
    try:
        data = json.loads(request.body)
        college_name= data['formData']['college_name']
        old_name= data['old_name']
        Department.objects.filter(department_name=old_name).update(department_name=college_name)
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)

def del_one(request):
    try:
        data = json.loads(request.body)
        college_name= data['del_id']
        Department.objects.filter(department_name=college_name).delete()
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)
